package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.minio.service.impl.FileUploadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Author:huzhongkui
 * Date: 2025-03-12 星期三 13:56:12
 * Description:
 */

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio",value = "enable",havingValue = "true")
public class MinioAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 定义MiniOClient的Bean对象
     */

    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {

        try {
            // 1.创建MinioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            // 2.判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // 3.创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                logger.info("桶已经存在");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("minioClient对象创建失败：{}", e.getMessage());
            throw new GuiguException(201, "minioClient对象创建失败");
        }


    }


    @Bean
    public FileUploadService fileUploadService(){
        return new FileUploadServiceImpl();
    }
}
